import { makeAutoObservable, runInAction } from "mobx"
import { reqLogin, reqGetUserInfo, reqLogout } from "@/api/user/loginUser";

export interface LoginParams {
  username: string;
  password: string;
}

class LoginUser {

  token = localStorage.getItem("token") || "" // 用户唯一标识
  name = "" // 用户名
  avatar = "" // 用户头像

  constructor () {
    // 将类的属性和更新属性的方法变为响应式的
    makeAutoObservable(this)
  }

  async login ({ username, password }: LoginParams) {
    const token = await reqLogin(username, password)
    runInAction(() => {
      this.token = token
      localStorage.setItem("token", token);
    })
  }

  async getUserInfo () {
    const { name, avatar } = await reqGetUserInfo()
    runInAction(() => {
      this.avatar = avatar
      this.name = name
    })
  }

  async logout () {
    await reqLogout()
    runInAction(() => {
      this.token = "";
      this.name = "";
      this.avatar = "";
      localStorage.removeItem("token");
    })
  }
}

// 向外暴露类的实例 
export default new LoginUser()